package com.chmingx.springcloud.controller;

import com.chmingx.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "paymentGlobalFallback") // 配置全局的fallback
public class OrderHystrixController {
    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        String result = paymentHystrixService.paymentInfo_OK(id);
        log.info(result);
        return result;
    }

    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentTimeoutFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
    })
    public String paymentInfo_Timeout(@PathVariable("id") Integer id) {
        String result = paymentHystrixService.paymentInfo_Timeout(id);
        log.info(result);
        return result;
    }

    public String paymentTimeoutFallback(@PathVariable("id") Integer id) {
        return "我是消费者80，对方支付系统繁忙，请稍后再试，或者自己运行出错，请检查自己";
    }

    @GetMapping("/consumer/payment/hystrix/global/{id}")
    @HystrixCommand // 服务报错后，使用降级兜底的方法
    public String paymentInfo_Global(@PathVariable("id") Integer id) {
//        int age = 10 / 0;
        String result = paymentHystrixService.paymentInfo_Timeout(id);
        log.info(result);
        return result;
    }

    public String paymentGlobalFallback() {
        return "Global异常处理信息，对方支付系统繁忙，请稍后再试，或者自己运行出错，请检查自己";
    }
}
